package com.ciwong.epaper.modules.me.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.me.adapter.WrongQuesPagerAdapter;
import com.ciwong.epaper.modules.me.bean.ServiceDetail;
import com.ciwong.epaper.modules.me.bean.WrongQuestion;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.FileUtil;
import com.ciwong.mobilelib.utils.ImageLoaderHelper;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 我的错题
 *
 * @author sugy
 * @version ciwong v.1.0 2015/9/15 10:43
 * @since ciwong v.1.0
 */
public class MyWrongQuesActivity extends BaseActivity
{
    private ViewPager viewPager;

    private View choiceQuesView, shortQuesView;

    private LinearLayout bottomLayout;

    private List<WrongQuestion> mQuesList = new ArrayList<WrongQuestion>();

    private Answer answer;

    private int currSelectdPointIndex = 0;// 当前选中的小圆点下标

    private TextView tvRefAnswer, tvUserAnswer, tvAnalyze, tvExample,
            tvNoOpenTip, tvCompositionScore;

    private ImageView ivUserAnswer;

    private Button btnToOpenService;

    private boolean loadImgIsSuccess;

    private View imgProBar, compositionView, noOpenView;

    private DisplayImageOptions imgOptions;

    /**
     * 开通服务requestCode
     */
    private static final int REQ_CODE_OPEN_SERVICE = 0;

    @Override
    protected void preCreate()
    {
        super.preCreate();
        answer = (Answer) getIntent()
                .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
    }

    @Override
    protected int setView()
    {
        return R.layout.activity_wrong_question;
    }

    @Override
    protected void findViews()
    {
        viewPager = (ViewPager) findViewById(R.id.ques_view_pager);

        // 选择题/填空题
        choiceQuesView = findViewById(R.id.wrong_choice_ques_view);
        tvRefAnswer = (TextView) findViewById(R.id.wrong_ques_ref_answer_tv);
        tvUserAnswer = (TextView) findViewById(R.id.wrong_ques_user_answer_tv);
        imgProBar = findViewById(R.id.pro_bar_wrong_ques_img);
        ivUserAnswer = (ImageView) findViewById(R.id.wrong_ques_user_answer_iv);
        tvAnalyze = (TextView) findViewById(R.id.wrong_ques_analyze_tv);

        // 开通服务
        noOpenView = findViewById(R.id.no_open_view);
        tvNoOpenTip = (TextView) findViewById(R.id.open_tip_tv);
        btnToOpenService = (Button) findViewById(R.id.to_open_service);

        // 简答题
        shortQuesView = findViewById(R.id.wrong_short_ques_view);
        compositionView = findViewById(R.id.my_work_layout);
        tvCompositionScore = (TextView) findViewById(R.id.my_composition_score);
        tvExample = (TextView) findViewById(R.id.wrong_example_work_tv);

        // 底部小圆点layout
        bottomLayout = (LinearLayout) findViewById(
                R.id.wrong_ques_bottom_point_view);
    }

    @Override
    protected void initEvent()
    {
        btnToOpenService.setOnClickListener(onClickListener);
        compositionView.setOnClickListener(onClickListener);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                    int positionOffsetPixels)
            {

            }

            @Override
            public void onPageSelected(int position)
            {
                if (bottomLayout.getChildCount() > 0)
                {
                    View oldPointView = bottomLayout
                            .getChildAt(currSelectdPointIndex);
                    if (oldPointView != null)
                    {
                        oldPointView.setSelected(false);
                    }
                    View pointView = bottomLayout.getChildAt(position);
                    if (pointView != null)
                    {
                        pointView.setSelected(true);
                        currSelectdPointIndex = position;
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state)
            {

            }
        });
    }

    View.OnClickListener onClickListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            int i = v.getId();
            if (i == R.id.to_open_service)
            {
//                MeJumpManager.jumpServices(R.string.go_back,
//                        MyWrongQuesActivity.this, 0);
                MeJumpManager.jumpToResourseCenterH5Activity(MyWrongQuesActivity.this,R.string.go_back,getResources().getString(R.string.resource_center));
                finish();
            }
            else if (i == R.id.my_work_layout)
            {
                Object userAnswer = compositionView.getTag();
                if (userAnswer != null && !userAnswer.toString().isEmpty())
                {
                    BaseJumpManager.jumpToScanImage(MyWrongQuesActivity.this,
                            R.string.go_back, userAnswer.toString());
                }
                else
                {
                    showToastAlert("资源不存在");
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data)
    {
        if (resultCode == RESULT_OK)
        {
            if (requestCode == REQ_CODE_OPEN_SERVICE)
            {// 开通服务成功后
                refreshIsOpenService();
            }
        }
    }

    @Override
    protected void init()
    {
        setTitleText(answer.getResourceName());
        if (null != answer && answer.getComment() != null && answer.getComment().length() > 0) {
            setRightBtnBG(R.mipmap.icon_teacher_comment);
            setRightBtnEnable(true);
            setRightBtnListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    DialogUtil.showCommentDialog(MyWrongQuesActivity.this,answer.getComment());
                }
            });
        }

    }

    @Override
    protected void loadData()
    {
        showMiddleProgressBar(getTitleText());
        MeDao.getInstance().getMyWrongQuestion(answer.getDoWorkId(),
                new BaseExtCallBack(MyWrongQuesActivity.this, EApplication.getInstance().getUserInfoBase().getUserId()+"")
                {

                    @Override
                    public void success(Object data)
                    {
                        List<WrongQuestion> wrongQuestions = (List<WrongQuestion>) data;
                        mQuesList.clear();
                        if (wrongQuestions != null)
                            mQuesList.addAll(wrongQuestions);

                        showData();
                        hideMiddleProgressBar();
                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        super.failed(errorCode, data);
                        showToastError(errorCode,data);
                        hideMiddleProgressBar();
                        //failed(data);
                    }

                    @Override
                    public void failed(Object data)
                    {
                        failed(-1,data);
                        //showToastError(String.valueOf(data));

                    }
                });
    }

    /**
     * 显示数据
     */
    private void showData()
    {
        if (!mQuesList.isEmpty())
        {
            refreshQuestionShow(0);

            WrongQuesPagerAdapter pagerAdapter = new WrongQuesPagerAdapter(
                    MyWrongQuesActivity.this, mQuesList);
            viewPager.setAdapter(pagerAdapter);
            viewPager.setCurrentItem(0);
            int pageSize = pagerAdapter.getCount();
            viewPager.setOffscreenPageLimit(pageSize - 1);

            addBottomPointView(pageSize);
        }
    }

    /**
     * 刷新UI
     *
     * @param currIndex
     */
    public void refreshQuestionShow(int currIndex)
    {
        if (currIndex >= 0 && currIndex < mQuesList.size())
        {
            final WrongQuestion question = mQuesList.get(currIndex);
            int qtype = question.getQtype();
            if (qtype <= 3)
            {// 选择题/填空题
                choiceQuesView.setVisibility(View.VISIBLE);
                shortQuesView.setVisibility(View.GONE);

                tvRefAnswer.setText(R.string.ref_answer);
                String refAnswer = question.getRefAnswer();
                if (!TextUtils.isEmpty(refAnswer))
                {
                    SpannableString ss = new SpannableString(refAnswer);
                    ss.setSpan(
                            new ForegroundColorSpan(getResources()
                                    .getColor(R.color.color_light_green)),
                            0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tvRefAnswer.append(ss);
                }

                tvUserAnswer.setText(R.string.user_answer);
                final String userAnswer = question.getUserAnswer();
                if (!TextUtils.isEmpty(userAnswer))
                {
                    if (qtype == 3)
                    { // 填空题
                        loadUserAnswerImg(userAnswer);
                        ivUserAnswer
                                .setOnClickListener(new View.OnClickListener()
                                {
                                    @Override
                                    public void onClick(View v)
                                    {
                                        if (loadImgIsSuccess)
                                        {// 加载成功
                                            MeJumpManager.jumpToScanImage(
                                                    MyWrongQuesActivity.this,
                                                    R.string.go_back,
                                                    userAnswer);
                                        }
                                        else
                                        {
                                            loadUserAnswerImg(userAnswer);
                                        }
                                    }
                                });

                        ivUserAnswer.setVisibility(View.VISIBLE);
                    }
                    else
                    {// 选择题
                        SpannableString userSs = new SpannableString(
                                userAnswer);
                        userSs.setSpan(
                                new ForegroundColorSpan(getResources()
                                        .getColor(R.color.score_red)),
                                0, userSs.length(),
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        tvUserAnswer.append(userSs);

                        ivUserAnswer.setVisibility(View.GONE);
                    }
                }
                else
                {
                    ivUserAnswer.setVisibility(View.GONE);
                }

                // 题目解析
                String solvingIdea = question.getSolvingIdea();
                if (!TextUtils.isEmpty(solvingIdea))
                {
                    tvAnalyze.setText(getString(R.string.question_analyze,
                            Html.fromHtml(solvingIdea)));
                }
                else
                {
                    tvAnalyze.setText("");
                }

            }
            else if (qtype == 6 || qtype == 7)
            {// 简答题
                shortQuesView.setVisibility(View.VISIBLE);
                choiceQuesView.setVisibility(View.GONE);

                // 参考范文
                tvExample.setText(question.getRefAnswer());

                final String tag = ImageLoaderHelper.getInstance()
                        .getImageCachePath(question.getUserAnswer()
                                + question.getDoodleUrl());

                // 我的作文
                compositionView.setTag(EConstants.FILE_PREFIX + tag);
                if (!new File(tag).exists())
                {
                    ThreadTask.getInstance().executorOtherThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            DisplayImageOptions options = new DisplayImageOptions.Builder()
                                    .imageScaleType(ImageScaleType.NONE)
                                    .build();
                            Bitmap bitmap1 = ImageLoader.getInstance()
                                    .loadImageSync(question.getUserAnswer(),
                                            options);
                            Bitmap bitmap2 = ImageLoader.getInstance()
                                    .loadImageSync(question.getDoodleUrl(),
                                            options);
                            FileUtil.merger(MyWrongQuesActivity.this,bitmap1, bitmap2, tag);
                        }
                    }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
                }

                // 作文得分
                tvCompositionScore.setText(question.getScore() + "分");
            }

            refreshIsOpenService();
        }
    }

    /**
     * 加载用户答案图片
     * 
     * @param userAnswer
     */
    private void loadUserAnswerImg(String userAnswer)
    {
        ImageSize size = new ImageSize(DeviceUtils.getScreenWdith(),
                R.dimen.word_pic_height);
        ivUserAnswer.setImageBitmap(null);
        startLoad: ImageLoader.getInstance().loadImage(userAnswer, size,
                getUserAnswerOption(), new ImageLoadingListener()
                {
                    @Override
                    public void onLoadingStarted(String s, View view)
                    {
                        imgProBar.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onLoadingFailed(String s, View view,
                            FailReason failReason)
                    {
                        loadImgIsSuccess = false;
                        imgProBar.setVisibility(View.GONE);
                        showToastError(R.string.load_img_fail);
                        if (ivUserAnswer != null)
                        {
                            ivUserAnswer.setImageResource(
                                    R.mipmap.lib_default_rect_failed);
                        }
                    }

                    @Override
                    public void onLoadingComplete(String s, View view,
                            Bitmap bitmap)
                    {
                        loadImgIsSuccess = true;
                        imgProBar.setVisibility(View.GONE);
                        if (ivUserAnswer != null)
                        {
                            ivUserAnswer.setImageBitmap(bitmap);
                        }
                    }

                    @Override
                    public void onLoadingCancelled(String s, View view)
                    {

                        imgProBar.setVisibility(View.GONE);
                    }
                });
    }

    /**
     * 获取用户答案图片option
     *
     * @return
     */
    private DisplayImageOptions getUserAnswerOption()
    {
        if (imgOptions == null)
        {
            imgOptions = new DisplayImageOptions.Builder().cacheInMemory(true)
                    .cacheOnDisk(true)
                    .showImageForEmptyUri(R.mipmap.lib_default_rect)
                    .showImageOnFail(R.mipmap.lib_default_rect_failed).build();
        }
        return imgOptions;
    }

    /**
     * 是否开通服务刷新显示
     */
    private void refreshIsOpenService()
    {
        ServiceDetail serviceDetail = ((EApplication) getApplication())
                .getServiceDetail();
        if (serviceDetail == null || serviceDetail.getSurplusData() <= 0)
        {// 未开通服务
            noOpenView.setVisibility(View.VISIBLE);
            tvAnalyze.setVisibility(View.GONE);
            tvExample.setVisibility(View.GONE);
            tvNoOpenTip.setText(getString(R.string.no_open_to_look_analyze,
                    serviceDetail == null ? ""
                            : serviceDetail.getServiceTypeName()));
        }
        else
        {// 已开通服务
            tvAnalyze.setVisibility(View.VISIBLE);
            tvExample.setVisibility(View.VISIBLE);
            noOpenView.setVisibility(View.GONE);
        }
    }



    /**
     * 添加底部小圆点
     */
    private void addBottomPointView(int pageSize)
    {
        bottomLayout.removeAllViews();
        for (int i = 0; i < pageSize; i++)
        {
            View itemPointView = View.inflate(this,
                    R.layout.item_wrong_ques_point, null);
            itemPointView.setSelected(i == viewPager.getCurrentItem());
            int size = DeviceUtils.dip2px(8);
            int margin = DeviceUtils.dip2px(5);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    size, size);
            params.setMargins(margin, 0, margin, 0);
            itemPointView.setLayoutParams(params);
            bottomLayout.addView(itemPointView, i);
        }
    }
}